#include "thread/thread_manage.h"
#include "thread/epoll_thread.h"
namespace weilin
{
	ThreadManage::ThreadManage() :
		m_status(STATUS_IDLE)
	{

	}

	ThreadManage::~ThreadManage()
	{
		if (AtomicGet<Status>(&m_status) == STATUS_START)
		{
			Stop(STOP_PEACE);
		}
	}

	bool ThreadManage::Init(const uint32_t& epoll_tread_num, const uint32_t& thread_pool_num)
	{
		if (AtomicCompareExchange<Status>(&m_status, STATUS_IDLE, STATUS_INIT) == false)
		{
			AtomicSet<Status>(&m_status, STATUS_FAIL);
			std::cout << FILE_LINE_FUNCTION << " error" << std::endl;
			return false;
		}
		m_epoll_thread_sp = boost::make_shared<EpollThread>(epoll_tread_num);
		m_thread_pool_sp = boost::make_shared<ThreadPool>(epoll_tread_num);
		m_epoll_thread_sp->Init();
		m_thread_pool_sp->Init();
		return true;
	}
	bool ThreadManage::Start()
	{
		if (AtomicCompareExchange<Status>(&m_status, STATUS_INIT, STATUS_START) == false)
		{
			AtomicSet(&m_status, STATUS_FAIL);
			std::cout << FILE_LINE_FUNCTION << " error" << std::endl;
			return false;
		}

		m_epoll_thread_sp->Start();
		m_thread_pool_sp->Start();
		return true;
	}

	bool ThreadManage::Stop(const StopMthod& stop_method)
	{
		if (AtomicCompareExchange<Status>(&m_status, STATUS_START, STATUS_STOP) == false)
		{
			AtomicSet<Status>(&m_status, STATUS_FAIL);
			std::cout << FILE_LINE_FUNCTION << " error" << std::endl;
			return false;
		}
		m_epoll_thread_sp->Stop(stop_method);
		m_thread_pool_sp->Stop(stop_method);
		return true;
	}

	boost::asio::io_service& ThreadManage::GetAcceptIoService()
	{
		return m_epoll_thread_sp->GetAcceptIoService();
	}

	boost::asio::io_service& ThreadManage::GetSocketIoService()
	{
		return m_epoll_thread_sp->GetSocketIoService();
	}
}
